package com.culture.config.common.util;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
public class JSONUtil {
	public static final ObjectMapper mapper = new ObjectMapper();
	
	public static String beanToJSONString(Object bean) {
		if(Objects.isNull(bean)) {
			log.error("beanToJSONString bean is null");
			return "{}";
		}		
		try {
			return mapper.writeValueAsString(bean);
		} catch (JsonProcessingException e) {
			log.error("beanToJSONString:{}",e);
		}
		return null;
	}
	
	public static <T> T jsonStringToBean(String jsonStr,Class<T> cls) {
		if(StringUtils.isBlank(jsonStr)) {
			log.error("jsonStringToBean jsonStr is empty.");
			return null;
		}		
		try {
			return mapper.readValue(jsonStr, cls);
		} catch (JsonProcessingException e) {
			log.error("jsonStringToBean:{}",e);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static Map<String,Object> jsonStringToMap(String jsonStr) {
		if(StringUtils.isBlank(jsonStr)) {
			log.error("jsonStringToBean jsonStr is empty.");
			return Collections.emptyMap();
		}		
		try {
			return mapper.readValue(jsonStr, Map.class);
		} catch (JsonProcessingException e) {
			log.error("jsonStringToBean:{}",e);
		}
		return Collections.emptyMap();
	}

	public <R> List<R> parseJSONArray(String jsonStr, Class<R> rClass){
        if(StringUtils.isBlank(jsonStr)){
            return Collections.emptyList();
        }        
        try {
            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class,rClass);
            return mapper.readValue(jsonStr, javaType);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }
        return Collections.emptyList();
    }
}
